package git.soulbgm.utils;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * 电子邮件工具类
 *
 * @author SoulBGM
 * @date 2021/07/26
 */
public class EmailUtil {

    private final static Map<String, String> SMTP_ADDRESS_MAP = new HashMap<>();

    private static LogUtil log = new LogUtil(EmailUtil.class);

    static {
        SMTP_ADDRESS_MAP.put("163.com", "smtp.163.com:25");
        SMTP_ADDRESS_MAP.put("qq.com", "smtp.qq.com:25");
        SMTP_ADDRESS_MAP.put("gmail.com", "smtp.gmail.com:587");
        SMTP_ADDRESS_MAP.put("126.com", "smtp.126.com:25");
        SMTP_ADDRESS_MAP.put("aliyun.com", "smtp.aliyun.com:465");
        SMTP_ADDRESS_MAP.put("sohu.com", "smtp.sohu.com:25");
        SMTP_ADDRESS_MAP.put("sina.com", "smtp.sina.com:25");
    }

    /**
     * 发送电子邮件
     *
     * @param sender    发送邮箱
     * @param username  用户名
     * @param password  密码
     * @param recipient 收件邮箱
     * @param subject   主题
     * @param text      文本
     */
    public static void sendEmail(String sender, String username, String password, String recipient, String subject, String text) {
        String mailAddress = sender.substring(sender.indexOf("@") + 1);
        String smtpAddress = SMTP_ADDRESS_MAP.get(mailAddress);
        if (smtpAddress == null) {
            throw new RuntimeException("库中没有"+mailAddress+"的smtp地址");
        }
        String[] split = smtpAddress.split(":");
        String smtpHost = split[0];
        String smtpPort = split[1];
        Properties properties = new Properties();
        properties.put("mail.smtp.host", smtpHost);
        properties.put("mail.smtp.port", smtpPort);
        properties.put("mail.smtp.ssl.enable", "true");
        properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLServerSocketFactory");
        properties.put("mail.smtp.auth", "true");

        Session session = Session.getDefaultInstance(properties);
        session.setDebug(true);
        MimeMessage message = new MimeMessage(session);
        Transport transport = null;
        try {
            Address fromAddress = new InternetAddress(sender);
            message.setFrom(fromAddress);
            Address address = new InternetAddress(recipient);
            message.setRecipient(Message.RecipientType.TO, address);
            message.setSubject(subject);
            message.setText(text);
            message.saveChanges();
            transport = session.getTransport("smtp");
            transport.connect(smtpHost, username, password);
            transport.sendMessage(message, message.getAllRecipients());
        } catch (Exception e) {
            log.error("{} 往 {} 发送邮件时发时异常", sender, recipient, e);
        }
    }

}
